<template>

  <el-dialog title="节点权限编辑" :visible.sync="visible" append-to-body width="500px" @closed="$emit('dialog-close')">

    <template v-if="!user.isSuperRole">
      <center>
        <h1 class="no-select">只有超级角色才能编辑节点权限</h1>
      </center>
    </template>
    <template v-else-if="!!data && data.type == 1">
      <center>
        <h1 class="no-select">超级角色无需编辑权限</h1>
      </center>
    </template>
    <template v-else>

      <el-tree ref="node-tree" :data="nodeTree" show-checkbox default-expand-all node-key="id" highlight-current :props="{label: 'title', children: 'children'}">
      </el-tree>

    </template>

    <template slot="footer">
      <el-button @click="visible = false" size="mini">{{ $t('page.form.cancel') }}</el-button>

      <template v-if="!!user.isSuperRole && !!data && data.type == 0">
        <el-button @click="submit" size="mini" type="primary" :loading="loading">{{ $t('page.form.submit') }}</el-button>
      </template>
    </template>

  </el-dialog>

</template>

<script>

import util from '@/libs/util';
import { mapState, mapActions } from 'vuex'
import ApiNode from '@/api/system.node'
import ApiMain from '@/api/system.role'

export default {
  mixins: [],
  components: {},
  data() {
    return {
      visible: false,
      loading: false,
      mounted: false,

      data: null,
      nodeTree: [],
    }
  },
  computed: {
    ...mapState('d2admin/user', {
      user: 'info',
    })
  },
  mounted() {
    this.fetchNodeTree();
  },
  updated() {

  },
  beforeDestroy() { },
  methods: {

    show(data) {
      this.visible = true;
      this.data = data;

      this.$nextTick(() => {
        if (!!this.data && !!this.$refs['node-tree']) {
          this.$refs['node-tree'].setCheckedKeys(this.data.nodeIdList.map(item => item.id));
        }
      });

    },

    async fetchNodeTree() {

      this.loading = true;

      try {
        var re = await ApiNode.tree({
          page: 1,
          limit: 500
        });
        this.nodeTree = Object.copy(re.tree);
      } catch (err) {
        this.nodeTree = [];
      }

      this.loading = false;
    },

    async submit() {

      var id = this.data.id;
      var nodeIdList = this.$refs['node-tree'].getCheckedKeys();

      this.loading = true;

      try {
        var req = { id, nodeIdList };

        await ApiMain.setAccess(req);
        this.$message({ message: this.$t('page.form.modifysuccessfully'), type: 'success' });
        this.visible = false;

      } catch (err) {

      }

      this.loading = false;
    },


  },
}

</script>

<style scoped>
</style>